/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.WebIDE.ejb.sessions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.sessions.exceptions.*;

/**
 *
 * @author huy
 */
@Stateless
public class MessagesFacade implements MessagesFacadeLocal, MessagesFacadeRemote {
    @PersistenceContext(unitName = "WebIDE-ejbPU")
    private EntityManager _em;
    @Resource
    private UserTransaction utx = null;
/*
    public void create(Messages messages) {
        _em.persist(messages);
    }

    public void edit(Messages messages) {
        _em.merge(messages);
    }
*/
    public void remove(Messages messages) {
        _em.remove(_em.merge(messages));
    }

    public Messages find(Object id) {
        return _em.find(Messages.class, id);
    }

    public List<Messages> findAll() {
        return _em.createQuery("select object(o) from Messages as o").getResultList();
    }


    public EntityManager getEntityManager() {
        return _em;
    }

    public void create(Messages messages) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Users userName = messages.getUserName();
            if (userName != null) {
                userName = em.getReference(userName.getClass(), userName.getUserName());
                messages.setUserName(userName);
            }
            em.persist(messages);
            if (userName != null) {
                userName.getMessagesCollection().add(messages);
                userName = em.merge(userName);
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findMessages(messages.getId()) != null) {
                throw new PreexistingEntityException("Messages " + messages + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void edit(Messages messages) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Messages persistentMessages = em.find(Messages.class, messages.getId());
            Users userNameOld = persistentMessages.getUserName();
            Users userNameNew = messages.getUserName();
            if (userNameNew != null) {
                userNameNew = em.getReference(userNameNew.getClass(), userNameNew.getUserName());
                messages.setUserName(userNameNew);
            }
            messages = em.merge(messages);
            if (userNameOld != null && !userNameOld.equals(userNameNew)) {
                userNameOld.getMessagesCollection().remove(messages);
                userNameOld = em.merge(userNameOld);
            }
            if (userNameNew != null && !userNameNew.equals(userNameOld)) {
                userNameNew.getMessagesCollection().add(messages);
                userNameNew = em.merge(userNameNew);
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = messages.getId();
                if (findMessages(id) == null) {
                    throw new NonexistentEntityException("The messages with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Messages messages;
            try {
                messages = em.getReference(Messages.class, id);
                messages.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The messages with id " + id + " no longer exists.", enfe);
            }
            Users userName = messages.getUserName();
            if (userName != null) {
                userName.getMessagesCollection().remove(messages);
                userName = em.merge(userName);
            }
            em.remove(messages);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public List<Messages> findMessagesEntities() {
        return findMessagesEntities(true, -1, -1);
    }

    public List<Messages> findMessagesEntities(int maxResults, int firstResult) {
        return findMessagesEntities(false, maxResults, firstResult);
    }

    private List<Messages> findMessagesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Messages as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            //em.close();
        }
    }

    public Messages findMessages(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Messages.class, id);
        } finally {
            //em.close();
        }
    }

    public int getMessagesCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Messages as o").getSingleResult()).intValue();
        } finally {
            //em.close();
        }
    }

}
